package cn.edu.swufe.surverpark.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.MessageDigest;
import java.util.Set;

import cn.edu.swufe.surverpark.model.BaseEntity;
/**
 * @author 陈龙 E-mail:529914446@qq.com
 * @version创建时间:2015年4月29日下午7:30:06 类说明
 */
public class DataUtil {

	/**
	 * 使用md5算法加密
	 */
	public static String md5(String src) {
		
		try {
			StringBuffer buffer = new StringBuffer();
			char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
					'B', 'C', 'D', 'E', 'F' };
			byte[] bytes = src.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] targ = md.digest(bytes);
			for (byte b : targ) {
				buffer.append(chars[(b >> 4) & 0x0F]);
				buffer.append(b & 0x0F);
			}
			return buffer.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
	
	public static Serializable deeplyCopy(Serializable src){
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(src);
			oos.close();
			baos.close();
			
			byte[] bytes = baos.toByteArray();
			ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			Serializable copy = (Serializable) ois.readObject();
			ois.close();
			bais.close();
			return copy;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
	
	public static String extractRightsIds(Set<? extends BaseEntity> baseEntities) {
		String temp = "";
		if(ValidateUtil.isValid(baseEntities)){
			for(BaseEntity r:baseEntities){
				temp += r.getId() + ",";
			}
			return temp.substring(0,temp.length()-1);
		}
		return temp;
	}
}
